package cn.wolfcode.wolf2w.business.respority;

import cn.wolfcode.wolf2w.business.domain.Note;
import cn.wolfcode.wolf2w.business.domain.Strategy;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 攻略数据访问层
 * 负责从Elasticsearch中检索攻略和游记数据
 */
@Repository
public class StrategyRepository {
    // 攻略索引名称
    private static final String INDEX = "strategy";
    @Autowired
    private RestHighLevelClient client;

    /**
     * 根据关键词搜索攻略数据
     * 
     * @param query 搜索关键词
     * @param size  返回记录数
     * @return 攻略列表
     * @throws IOException Elasticsearch操作异常
     */
    public List<Strategy> search(String query, int size) throws IOException {
        // 创建搜索源构建器
        SearchSourceBuilder ssb = new SearchSourceBuilder();

        // 设置多字段匹配查询条件，匹配title、summary、subTitle字段
        ssb.query(QueryBuilders.multiMatchQuery(query, "title", "summary", "subTitle"));
        // 设置返回记录数量
        ssb.size(size);
        // 创建搜索请求，指定索引和搜索源
        SearchRequest request = new SearchRequest(INDEX).source(ssb);

        // 执行搜索操作
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 初始化结果列表
        List<Strategy> list = new ArrayList<>();
        // 遍历搜索结果
        for (SearchHit hit : response.getHits().getHits()) {
            // 获取文档源数据
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            // 提取攻略字段信息
            String title = sourceAsMap.get("title").toString();
            String subTitle = sourceAsMap.get("subTitle").toString();
            String summary = sourceAsMap.get("summary").toString();
            // 创建攻略对象
            Strategy strategy = new Strategy(null, title, subTitle, summary);

            // 添加到结果列表
            list.add(strategy);
        }
        // 返回搜索结果
        return list;
    }
    

}